package dyyx.util;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件读写工具类
 * 
 * @author dugang
 *
 */
public abstract class FileUtil {

	private static final int BUF_SIZE = 512;

	public static void close(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (Throwable e) {

		}
	}

	public static String readString(String file, String charset) throws Exception {
		byte[] bytes = readBytes(file);
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		if (charset == null) {
			charset = CommUtil.UTF8;
		}
		return new String(bytes, charset);
	}

	/**
	 * 批量读取 ，测试 是否能读取 /proc/sys/fs/file-nr 所有内容
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static byte[] readBytes(String file) throws Exception {
		InputStream is = null;
		try {
			is = new FileInputStream(new File(file));
			return toBytes(is);
		} finally {
			close(is);
		}
	}
	
	public static void write(String file,byte[]bytes) throws Exception {
		OutputStream os = null;
		try {
			os = new FileOutputStream(new File(file));
			os.write(bytes);
		} finally {
			close(os);
		}
	}

	private static byte[] toBytes(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[BUF_SIZE];
		int len = 0;
		while ((len = is.read(buf)) != -1) {
			if (len > 0) {
				bos.write(buf, 0, len);
			}
		}
		return bos.toByteArray();
	}

	/**
	 * 不要使用该方法!!!
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static String readStringOneByteOnce(String file,String charset) throws Exception {
		byte[] bytes = FileUtil.readBytesOneByteOnce(file);
		if(CommUtil.isBlank(charset)){
			charset = CommUtil.UTF8;
		}
		String str = new String(bytes, charset);
		return str;
	}

	/**
	 * 不要使用该方法 读取 /proc/sys/fs/file-nr 只能读到第一个字节！！！
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static byte[] readBytesOneByteOnce(String file) throws Exception {
		InputStream is = null;
		try {
			is = new FileInputStream(new File(file));
			return toBytesOneByteOnce(is);
		} finally {
			close(is);
		}
	}

	@Deprecated
	private static byte[] toBytesOneByteOnce(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int tmp = 0;
		while ((tmp = is.read()) != -1) {
			bos.write(tmp);
		}

		return bos.toByteArray();
	}

}
